//
//  main.m
//  NSStreamTest
//
//  Created by wangrui on 14-9-11.
//  Copyright (c) 2014年 PPS. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TestClass : NSObject<NSStreamDelegate>
@property(nonatomic)NSInteger location;
- (void)doTestInputStream;
- (void)doTestOutputStream;
@end

@implementation TestClass

- (void)doTestInputStream {
	NSString *path = @"/Users/wangrui/Desktop/stream.txt";
	
	NSInputStream *readStream = [[NSInputStream alloc]initWithFileAtPath:path];
	[readStream setDelegate:self];
	
	[readStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
	[readStream open];
}

- (void)doTestOutputStream {
	NSString *path = @"/Users/wangrui/Desktop/stream-write.txt";
	
	NSOutputStream *writeStream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
	[writeStream setDelegate:self];
	
	[writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
	[writeStream open];
}

- (NSData *)dataWillWrite {
	static  NSData *data = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		data = [NSData dataWithContentsOfFile:@"/Users/wangrui/Desktop/stream.txt"];
	});
	
	return data;
}

#pragma mark - NSStream Delegate
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
	switch (eventCode) {
		case NSStreamEventHasBytesAvailable:{
			
			uint8_t buf[1024];
			
			NSInputStream *reads = (NSInputStream *)aStream;
			NSInteger blength = [reads read:buf maxLength:sizeof(buf)];
			NSData *data = [NSData dataWithBytes:(void *)buf length:blength];
			
			NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
			NSLog(@"%@",string);
		}
			break;
					
		//下面2个事件主要是对于写的 outStream
		case NSStreamEventHasSpaceAvailable: {
			
			NSInteger bufSize = 5;
			uint8_t buf[bufSize];
			
			if (self.location + bufSize > [self dataWillWrite].length) {
				[[self dataWillWrite] getBytes:buf
										 range:NSMakeRange(self.location, self.location + bufSize - [self dataWillWrite].length)];
			}
			else {
				[[self dataWillWrite] getBytes:buf range:NSMakeRange(self.location, bufSize)];
			}
			
			NSOutputStream *writeStream = (NSOutputStream *)aStream;
			[writeStream write:buf maxLength:sizeof(buf)];
			
			self.location += bufSize;
			if (self.location >= [[self dataWillWrite] length] ) {
				[aStream close];
			}
			
		}
			break;
			
		case NSStreamEventEndEncountered: {
			[aStream close];
		}
			break;
		
		//错误和无事件处理
		case NSStreamEventErrorOccurred:{
			
		}
			break;
		case NSStreamEventNone:
			break;
		
		//打开完成
		case NSStreamEventOpenCompleted: {
			NSLog(@"NSStreamEventOpenCompleted");
			
			
		}
			break;
			
		default:
			break;
	}
}

@end



int main(int argc, const char * argv[])
{

	@autoreleasepool {
	    
		__strong TestClass *test = [TestClass new];
		[test doTestOutputStream];
		
		[[NSRunLoop currentRunLoop] run];

	}
    return 0;
}

